package com.gk.chat.utils;


import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * rsa非对称加密工具类
 */
public class RSAUtil {

    @Value("${rsa.private-key}")
    private String privateKey;

    //用私钥解密
    public static String decrypt(String encryptedData, String privateKey) throws Exception {
        byte[] encryptedBytes= Base64.getDecoder().decode(encryptedData);
        PrivateKey key=getPrivateKey(privateKey);

        Cipher cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    //从字符串加载私钥
    private static PrivateKey getPrivateKey(String privateKey) throws Exception {
        String cleanedKey=privateKey
                .replace("-----BEGIN PRIVATE KEY-----","")
                .replace("-----END PRIVATE KEY-----","")
                .replaceAll("\\s","");
        byte[] keyBytes=Base64.getDecoder().decode(cleanedKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory= KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    //从字符串加载公钥
    private static PublicKey getPublicKey(String publicKey) throws Exception {
        String cleanedKey=publicKey
                .replace("-----BEGIN PUBLIC KEY-----","")
                .replace("-----END PUBLIC KEY-----","")
                .replaceAll("\\s","");
        byte[] keyBytes=Base64.getDecoder().decode(cleanedKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory= KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }
}
